<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
//use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Queue\Capsule\Manager;
use Session;
use DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Log;
use App\Http\Requests\CreateCouponRequest;
use App\Http\Requests\UpdateCouponRequest;
use App\Coupon;
use App\UserCoupon;
use App\Activity;
use App\BankShop;
use App\StateConfig;
use Illuminate\Support\Facades\Auth;

class CouponController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

	public function index(Request $request) {
		// 查看当前菜单可使用的功能按钮
		$uri = $request->path();
		$data['optionArr'] =  $this->checkMenuOption($uri);
		/**
		 *  判断当前登录账号，如果是第三方网点公司账号，则查询显示当前网点的数据
		 *  如果不是，则默认显示所有
		 */
		$adminUser = Auth::user();
		$phone = $adminUser->name;
		$bank_id = BankShop::getIdByPhone($phone);
		if($bank_id){
			$couponObj = Coupon::where('is_del',1)->where('bank_show_id',$bank_id)->get();
		}else{
			$couponObj = Coupon::where('is_del',1)->get();
		}

//		dd($couponObj);
		$data['coupons'] = $couponObj;

		// 检查优惠券是否有用户使用或者领取
		$use = count(DB::table('user_coupon')->where('coupon_id',1)->get());

		return view('coupon.list')->with($data);
	}

	public function create(Request $request)
	{
		// 获取网点列表
		$data['bankShop'] = BankShop::getAllBankShopId();
		$data['activityS'] = Activity::getActivityId(); // 选择活动
//		dd($data['activityS']);
		$data['CouponType'] = StateConfig::getAllState('couponType');// 获取订单的状态


//		dd($data['CouponType'] );
		return view('coupon.create')->with($data);
	}


	public function store(CreatecouponRequest $request){
        $coupons = new coupon();
        $coupons->bank_show_id =$request->bank_show_id;
		$bank_show_name =DB::table('bank_show')->where('id',$request->bank_show_id)->pluck('shopName');
		$coupons->bank_show_name =$bank_show_name[0];

        $coupons->activity_id =$request->activity_id;
        $coupons->name =$request->name;
        $coupons->cType =$request->cType;
		$coupons->cType_name =state_config('couponType',$request->cType);
        $coupons->mixMoney =$request->mixMoney;
        $coupons->money =$request->money;
        $coupons->discount =$request->discount;
        $coupons->cDesc =$request->cDesc;
        $coupons->remark =$request->remark;

        if($request->validity){
        	if(strpos($request->validity,' - ')){
		        $validityArr = explode(' - ',$request->validity);
		        $coupons->startTime = $validityArr[0];
		        $coupons->endTime = $validityArr[1];
	        }else{
		        $coupons->validity = $request->validity;
	        }
        }

        if($coupons->save()){
        	if($request->activity_id){
				// 更新活动表的状态
		        $affectId= Activity::where('id',$request->activity_id)->update([
			        'state'=>2
		        ]);
	        }

	        $adminUser = Auth::user();
	        if($adminUser){
		        $userId = $adminUser->id;
		        $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').' 新增了【  '.$request->name.' 】优惠券';
		        adminOperationLog($request,$userId,$logs);
	        }

            return redirect('coupon/list')->with('success','新增成功');
        }else{
            return redirect()->back()->withInput();
        }
}


	public function edit($id)
	{
		$couponInfo = coupon::find($id);
		$data['couponInfo'] = $couponInfo;
		$data['bankShop'] = BankShop::getAllBankShopId();
		$data['activityS'] = Activity::getActivityId();
		$data['CouponType'] = StateConfig::getAllState('couponType');// 获取订单的状态

		return view('coupon.edit')->with($data);

	}


    public function update(UpdatecouponRequest $request, $id){
        $coupons = coupon::find($id);
	    $coupons->bank_show_id =$request->bank_show_id;
	    $coupons->activity_id =$request->activity_id;
	    $coupons->name =$request->name;
	    $coupons->cType =$request->cType;
	    $coupons->cType_name =state_config('couponType',$request->cType);
	    $coupons->cDesc =$request->cDesc;
	    $coupons->remark =$request->remark;
	    if($request->cType == 1){
		    $coupons->money =$request->money;
		    $coupons->mixMoney =$request->mixMoney;
		    $coupons->discount =0;
	    }else if($request->cType == 2){
		    $coupons->money =0;
		    $coupons->mixMoney =0;
		    $coupons->discount =$request->discount;
	    }

	    if($request->validity){
		    if(strpos($request->validity,' - ')){
			    $validityArr = explode(' - ',$request->validity);
			    $coupons->startTime = $validityArr[0];
			    $coupons->endTime = $validityArr[1];
			    $coupons->validity = 0;
		    }else{
			    $coupons->validity = $request->validity;
			    $coupons->startTime = NULL;
			    $coupons->endTime = NULL;
		    }
	    }

        if(!$coupons->save()){
            return Redirect::back()->withInput()->withErrors(['fail' => trans('message.updateFail')]);
        }

	    if($request->activity_id){
		    // 更新活动表的状态
		    $affectId= Activity::where('id',$request->activity_id)->update([
			    'state'=>2
		    ]);
	    }


	    $adminUser = Auth::user();
	    if($adminUser){
		    $userId = $adminUser->id;
		    $logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'编辑了【 '.$request->name.' 】优惠券';
		    adminOperationLog($request,$userId,$logs);
	    }

        return Redirect::to(url('coupon/list'))->with('success', trans('message.updateSuccess'));

    }

	public function delete(Request $request)
	{
		$cid = $request->id;
	    if(!$cid){
            return '-1';
        }

        if($cid == 1 || $cid==2){
			return '-2';
        }

        //  del
//        $affectId = coupon::where('id',$request->id)->delete();
		$affectId= coupon::where('id',$cid)->update([
			'is_del'=>-1
		]);
        if(!$affectId){
            return -1;
        }
		$name = coupon::getNameById($cid);
		$adminUser = Auth::user();
		if($adminUser){
			$userId = $adminUser->id;
			$logs = $adminUser->name.'在'.date('Y-m-d H:i:s').'删除了优惠券：【 '.$name.' 】';
			adminOperationLog($request,$userId,$logs);
		}

        return 1;
	}

	// 优惠券统计
	public function getCouponUseStatistics(Request $request)
	{

		$phone = '';
		// 手机号
		if ($request->input('phoneS')) {
			$phone = trim($request->input('phoneS'));
		}
		$coupons = array();
		$phoneArr = array(); // 日期数组
		$noUseArr = array();   // 未使用数组
		$useArr = array();   // 使用数组
		$expArr = array();   // 过期数组

		$couponsList = coupon::getCouponEveryUserTotal($phone);
//		dd($couponsList);
		if ($couponsList) {
			$noUseTotalArr = array(); // 未使用
			$useTotalArr = array(); // 已使用
			$expTotalArr = array(); // 过期
			foreach ($couponsList as $key => $value) {
				$coupons[$key]['phone'] = $value->phone;
				$coupons[$key]['nickname'] = $value->nickname;
				$coupons[$key]['notUsedTotal'] = isset($value->notUsedTotal) ? $value->notUsedTotal : 0;   // 未使用量
				$coupons[$key]['usedTotal'] = isset($value->usedTotal) ? $value->usedTotal : 0; //使用
				$coupons[$key]['expireTotal'] = isset($value->expireTotal) ? $value->expireTotal : 0;   // 过期

				// 获取手机号数据
				$phoneArr[] = $value->phone;
				// 拼接使用数、未使用数、过期数
				$noUseTotalArr[$key]['phone'] = isset($value->phone) ? $value->phone : 0;   // 手机号
				$noUseTotalArr[$key]['notUsedTotal'] = isset($value->notUsedTotal) ? $value->notUsedTotal : 0;   // 未使用

				$useTotalArr[$key]['phone'] = isset($value->phone) ? $value->phone : 0;   // 手机号
				$useTotalArr[$key]['usedTotal'] = isset($value->usedTotal) ? $value->usedTotal : 0;   // 使用

				$expTotalArr[$key]['phone'] = isset($value->phone) ? $value->phone : 0;   // 手机号
				$expTotalArr[$key]['expireTotal'] = isset($value->expireTotal) ? $value->expireTotal : 0;   // 过期

			}
			// 线形图数据---------------------------------------------------------------------------
			if ($phoneArr) {
				foreach ($phoneArr as $key => $value) {
					// 未使用数组
					for ($i = 0; $i < count($noUseTotalArr); $i++) {
						if ($value == $noUseTotalArr[$i]['phone']) {
							$noUseArr[$key] = (int)$noUseTotalArr[$i]['notUsedTotal'];
							break;
						} else {
							$noUseArr[$key] = 0;
						}
					}
					// 使用
					for ($i = 0; $i < count($useTotalArr); $i++) {
						if ($value == $useTotalArr[$i]['phone']) {
							$useArr[$key] = (int)$useTotalArr[$i]['usedTotal'];
							break;
						} else {
							$useArr[$key] = 0;
						}
					}
					// 过期
					for ($i = 0; $i < count($expTotalArr); $i++) {
						if ($value == $expTotalArr[$i]['phone']) {
							$expArr[$key] = (int)$expTotalArr[$i]['expireTotal'];
							break;
						} else {
							$expArr[$key] = 0;
						}
					}
				}
			}
		}

//		dd($expArr);
			$phoneArr = json_encode($phoneArr);
			$noUseArr = json_encode($noUseArr);
			$useArr = json_encode($useArr);
			$expArr = json_encode($expArr);
			$data['phoneArr'] = $phoneArr;
			$data['noUseArr'] = $noUseArr;
			$data['useArr'] = $useArr;
			$data['expArr'] = $expArr;
			$data['couponStatistics'] = $coupons;
			$data['phoneS'] = $request->input('phoneS');

			return view('coupon.coupon_statistic')->with($data);


	}



}





